<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace TpAmisAdmin\Admin\middleware;


use app\Request;
use app\services\system\admin\AdminAuthServices;
use think\facade\Config;
use TpAmisAdmin\Admin\common\utils\JwtAuth;
use TpAmisAdmin\Admin\model\Admin;
use TpAmisAdmin\Admin\service\CacheService;

/**
 * 后台登陆验证中间件
 * Class AdminAuthTokenMiddleware
 * @package app\adminapi\middleware
 */
class AdminAuthTokenMiddleware
{
    /**
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 吴汐
     * @email 442384644@qq.com
     * @date 2023/04/07
     */
    public function handle(Request $request, \Closure $next)
    {
        $token = trim(ltrim($request->header(Config::get('cookie.token_name', 'authorization')), 'Bearer'));
        if (!$token) {
            $token = trim(ltrim($request->get('token')));
        }

        $adminInfo = $this->parseToken($token);
        if (!$adminInfo) {
            return app('json')->fail('token无效或已过期', [], 401);
        }

        return $next($request);
    }


    /**
     * 获取Admin授权信息
     * @param string $token
     * @param int $code
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function parseToken(string $token, int $code = 110003): array
    {
        /** @var CacheService $cacheService */
        $cacheService = app()->make(CacheService::class);

        if (!$token || $token === 'undefined') {
            throw new \Exception($code);
        }
        /** @var JwtAuth $jwtAuth */
        $jwtAuth = app()->make(JwtAuth::class);
        //设置解析token
        [$id, $type, $pwd] = $jwtAuth->parseToken($token);

        //检测token是否过期
        $md5Token = md5($token);
        if (!$cacheService->has($md5Token) || !$cacheService->get($md5Token)) {
            throw new \Exception($code);
        }

        //验证token
        try {
            $jwtAuth->verifyToken();
        } catch (\Throwable $e) {
            if (!request()->isCli()) {
                $cacheService->delete($md5Token);
            }
            throw new \Exception($code);
        }

        //获取管理员信息
        $adminInfo = Admin::where('id', $id)->where('status', 1)->find();
        if (!$adminInfo || !$adminInfo->id) {
            if (!request()->isCli()) {
                $cacheService->delete($md5Token);
            }
            throw new \Exception($code);
        }
        if ($pwd !== '' && $pwd !== md5($adminInfo->pwd)) {
            throw new \Exception($code);
        }

        $adminInfo->type = $type;
        return $adminInfo->hidden(['pwd', 'is_del', 'status'])->toArray();
    }



    /**
     * 保存提交数据
     * @param $adminId
     * @param $postData
     */
    protected function saveProduct($adminId, $postData)
    {
        /** @var CacheServices $cacheService */
        $cacheService = app()->make(CacheService::class);
        $cacheService->setDbCache($adminId . '_product_data', $postData, 68400);
    }
}
